package com.blog.wu.myblog.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author wuyanshen
 * @Date 2019-01-03 11:27 AM
 * @Discription Redis操作类
 */
@Service
public class RedisService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void setString(String key,Object value,Long time) {
        this.setObject(key,value,time);
    }

    public void setString(String key,Object value) {
        this.setObject(key,value,null);
    }

    public void setList(String key,List<String> list,Long time) {
        this.setObject(key,list,time);
    }

    public String getString(String key) {
        return (String) this.getObject(key);
    }

    public void remove(String key) {
        this.removeObject(key);
    }

    public List<String> getList(String key) {
        return (List<String>) this.getObject(key);
    }


    public Object getObject(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }

        String str = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(str)) {
            return str;
        }

        List<String> list = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (list.size()>0) {
            return list;
        }

        return null;
    }

    public void removeObject(String key) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        stringRedisTemplate.delete(key);
    }


    public void setObject(String key,Object value,Long time) {
        if (StringUtils.isEmpty(key) || value == null) {
            return;
        }
        //判断类型
        //如果是String类型
        if (value instanceof String) {
            String strVal = (String) value;
            if (time != null) {
                stringRedisTemplate.opsForValue().set(key, strVal, time,TimeUnit.SECONDS);
            } else {
                stringRedisTemplate.opsForValue().set(key,strVal);
            }
            System.out.println("String添加成功");
            return;
        }

        //如果是List类型
        if (value instanceof List) {
            List<String> list = (List<String>) value;
            for (String s:list) {
                if (time != null) {
                    stringRedisTemplate.opsForList().leftPush(key, s, Long.toString(time));
                } else {
                    stringRedisTemplate.opsForList().leftPush(key, s);
                }
            }
            System.out.println("List添加成功");
            return;
        }
    }


}
